package com.hmjk.health.background.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.NetService;
import com.hmjk.health.util.TODO_DATA;

public class ToDoUpdated extends DataUpdated{
	private static String TAG = ToDoUpdated.class.getSimpleName();
	//public static final String TYPE_FAMILY = "family";
	//public static final String TYPE_USER = "user";
	//public static final String TYPE_ALL = "all";
	
	private static HashMap<String,TODO_DATA> mMap = new HashMap<String,TODO_DATA>();
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	public ToDoUpdated(HealthApp app, DataManager dm) {
		super(app, dm);
		UPDATE_TIME = 2 * 60 * 1000;
	}

	@Override
	public void setUserData(Object data) {
		// TODO Auto-generated method stub
		reqTime = 0;
	}

	@Override
	public long delay() {
		long curMs = System.currentTimeMillis();
		long del = curMs - upTime;
		logd("delay curMs="+curMs+" upTime="+upTime+" del="+del);
		if(del >= UPDATE_TIME){
			logd("delay 0");
			return 0;
		}else{
			logd("delay (UPDATE_TIME - del) = "+(UPDATE_TIME - del));
			return (UPDATE_TIME - del);
		}
	}
	
	private void doRequest(String uid){		
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.GET_TODO_LIST);
		si.putExtra("uid", uid);
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_TODO_LIST" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}

	@Override
	public boolean grab() {
		String uid = mApp.getUID();
		logd("grab uid="+uid);
		if(uid == null)
			return false;
		
		long curMs = System.currentTimeMillis();
		logd("grab curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > UPDATE_TIME){
			doRequest(uid);
			reqTime = curMs;
			logd("grab req sent!");
			return true;
		}
		return false;
	}

	@Override
	public boolean grabByUser() {
		String uid = mApp.getUID();
		logd("grabByUser uid="+uid);
		if(uid == null)
			return false;
		
		long curMs = System.currentTimeMillis();
		logd("grabByUser curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > MIN_QUERY_DUR * 1000){
			doRequest(uid);
			reqTime = curMs;
			logd("grabByUser req sent!");
			return true;
		}
		return false;
	}

	@Override
	public void receive(String stamp, String sjson) {
		if(stamp.startsWith("GET_TODO_LIST")){
			if(sjson != null){
				boolean update = false;
				try {
					JSONObject json = new JSONObject(sjson);
					int code = json.getInt("code");
					if(code == 200){
						String state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							JSONObject recdata = json.getJSONObject("recdata");
							if(recdata != null){
								upTime = System.currentTimeMillis();
								mMap.clear();
								if(recdata.has("remberarr")){
									JSONArray arr = recdata.getJSONArray("remberarr");
									int size = arr.length();
									for(int i = 0; i < size; i++){
										JSONObject o = arr.getJSONObject(i);
										TODO_DATA d = new TODO_DATA();
										d.rid = o.getString("rid");
										d.code = o.getString("rembercode");
										//temp code for data error -- start
										String rembertime = o.getString("rembertime");
										if(rembertime.trim().isEmpty() || rembertime.equalsIgnoreCase("NULL")){
											d.time = System.currentTimeMillis();
										}else{
										//temp code for data error -- end
										d.time = o.getLong("rembertime");
										}
										d.uid = o.getString("uid");
										d.fid = o.getString("fid");
										d.tid = o.getString("tid");
										if(o.has("mark")){
										JSONObject mark = o.getJSONObject("mark");
										d.mark = mark.toString();
										}
										mMap.put(d.rid, d);
									}
								}
								update = true;
							}
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
				i.putExtra("type",DataManager.F_TODO);
				i.putExtra("state", update);
				mApp.sendBroadcast(i);
			}
		}else if(stamp.startsWith("COMMIT_TODO")){
			if(sjson != null){
				String state = "af";
				int code = 400;
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					if(code == 200){
						state = json.getString("state");
						if(state.equalsIgnoreCase("00")){	
							JSONObject rec = json.getJSONObject("recdata");
							JSONArray statearr = rec.getJSONArray("statearr");
							int size = statearr.length();
							for(int i=0; i<size; i++){
								JSONObject e = statearr.getJSONObject(i);
								String rid = e.getString("rid");
								String s = e.getString("remberstate");
								if(s.equals("00")){
									mMap.remove(rid);
								}
							}
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					state = "af";
				}
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_TODO);
				i.putExtra("state", state);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
		}
		
	}
	
	@Override
	public Object check(String[] arg) {
		ArrayList<TODO_DATA> l = new ArrayList<TODO_DATA>();
		Iterator<Entry<String, TODO_DATA>> iter = mMap.entrySet().iterator();
		while(iter.hasNext()){
			Entry<String,TODO_DATA> entry = (Entry<String,TODO_DATA>) iter.next();
			String key = entry.getKey();
			TODO_DATA d = entry.getValue();
			TODO_DATA c = d.clone();
			l.add(c);
		}

		return l;
	}

	@Override
	public boolean commit(Object data) {
		TODO_DATA d = (TODO_DATA) data;
		Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
		si.putExtra("sub_act", NetService.COMMIT_TODO);
		si.putExtra("uid", mApp.getUID());
		si.putExtra("rid", d.rid);
		si.putExtra("rembercode", d.code);
		si.putExtra("remberstate",(d.agree?"1":"2"));
		long longtime = System.currentTimeMillis();
		si.putExtra("rembertime", longtime);
		
		Time t = new Time();
		t.setToNow();
		String stamp = "COMMIT_TODO" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
		return true;
	}

	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}
}
